
# 导入 socket、sys 模块
import socket
import sys

# 创建 socket 对象
import threading

serversocket = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名
host = socket.gethostname()

port = 9999

# 绑定端口号
serversocket.bind((host, port))

# 设置最大连接数，超过后排队
serversocket.listen(5)

clien_list = []

def recv_message(clientsocket):
    while True:
        c_msg = clientsocket.recv(1024).decode()
        print(c_msg)

        if c_msg == "stop":
            clientsocket.close()
            break
        for client in clien_list:
            if clientsocket != client:
                relay(client, c_msg)

def send_message(clientsocket):
    while True:
        # 接收小于 1024 字节的数据
        msg = input("请输入：")

        clientsocket.send(msg.encode('utf-8'))

def relay(clientsocket, msg):
    clientsocket.send(msg.encode('utf-8'))

while True:
    # 建立客户端连接
    clientsocket, addr = serversocket.accept()

    clien_list.append(clientsocket)

    print("连接地址: %s" % str(addr))


    send_thread = threading.Thread(target=send_message, args=(clientsocket,))  # 注意传入的参数一定是一个元组!
    send_thread.start()

    recv_thread = threading.Thread(target=recv_message, args=(clientsocket,))
    recv_thread.start()



